import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKEN_HEADER
} from '@/config/app';
import store from '@/store'

function fullUrl(url) { /* 判断url是否为完整路径 */
	return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}

//表单序列化
function serialize(data) {
	let list = [];
	Object.keys(data).forEach(ele => {
		list.push(`${ele}=${data[ele]}`)
	})
	return list.join('&');
};

// function addQueryString(params) {
// 	let paramsData = ''
// 	Object.keys(params).forEach(function(key) {
// 		paramsData += key + '=' + encodeURIComponent(params[key]) + '&'
// 	})
// 	return paramsData.substring(0, paramsData.length - 1)
// }
/**
 * 发送请求
 */
export default function request(config = {}) {

	config.url = fullUrl(config.url)?config.url:HTTP_REQUEST_URL + config.url
	config.data = config.data || {}
	config.params = config.params || {}
	config.headers = Object.assign(HEADER, config.headers)
	config.method = config.method || 'GET'
	config.method = config.method.toUpperCase()
	// config.header['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;

	// config.header['Tenant-Id'] = website.tenantId;
	// config.header['shopId'] = website.shopId;

	// if (uni.getStorageSync('token')) {
	// 	config.header[TOKEN_HEADER] = 'bearer ' + uni.getStorageSync('token');
	// }

	if (store.state.token) config.headers[TOKEN_HEADER] = 'bearer ' + store.state.token;

	if (config.method === 'POST' && JSON.stringify(config.params) != '{}') {
		config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
		config.data = config.params;
		// const params = serialize(config.params);
		// config.url += config.url.indexOf('?') === -1 ? `?${params}` : `&${params}`
	}else if(config.method === 'POST'){
		config.headers['Content-Type'] = 'application/json;charset=UTF-8';
	}
	return new Promise((reslove, reject) => {
		uni.request({
			url: config.url,
			method: config.method,
			header: config.headers,
			data: config.method === 'GET'?config.params:config.data,
			success: (res) => {

				//获取状态码
				const status = res.data.code || res.status || res.statusCode;
				const message = res.data.msg || res.data.error_description || '未知错误';

				//如果是401则跳转到登录页面
				if (status === 401) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else if (status !== 200) {
					reject(message);
				} else {
					reslove(res.data);
				}
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}
